package com.ptswitch.material.pages.contract;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.tapestry5.util.ValueLabel;
import org.hxzon.util.EMailUtil;
import org.hxzon.util.EMailUtil.EMail;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.contract.ContractAttachment;
import com.ptswitch.material.pages.base.MaterialBasePage;
import com.ptswitch.material.service.ContractService;

public class SendEMail extends MaterialBasePage {
    @InjectPage
    private ViewContract viewContract;
    @Inject
    private ContractService contractSer;
    @Property
    private EMail email;
    @Property
    private List<Uzer> userForEMailAddresses;
    @Property
    private ValueLabel<Uzer> emailAddressLabel = new ValueLabel<Uzer>() {
        public String toLabel(Uzer value, int index) {
            return value.getRealname() + "(" + value.getEmail() + ")";
        }
    };
    @Property
    private ValueLabel<ContractAttachment> attachmentLabel = new ValueLabel<ContractAttachment>() {
        public String toLabel(ContractAttachment value, int index) {
            return value.getFileName();
        }
    };
    @Property
    private Contract contract;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(String id) {
        contract = contractSer.findById(id, ContractService.Init_Uploads);
        checkUserIsEqual(contract.getCreater());
        email = getMaterialUtil().newEMail();
        email.setUsername(getVisitor().getEmail());
        userForEMailAddresses = new ArrayList<Uzer>();
        userForEMailAddresses.add(contract.getCreater());
        userForEMailAddresses.add(contract.getAuditor());
        userForEMailAddresses.add(contract.getFinancial());
        userForEMailAddresses.add(contract.getProduction());
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return contract.getId();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "sendEMail")
    Object sendEMail() {
        checkUserIsEqual(contract.getCreater());
        //send email to supplier
        email.setFrom(email.getUsername());
        for (Uzer user : userForEMailAddresses) {
            email.addTo(user.getEmail());
        }
        email.addText(email.getTmpTextContent());
        for (ContractAttachment attach : contract.getAttachments()) {
            email.addAttachment(attach.getFileName(), getWebUtil().getRealFilePath(attach));
        }
        EMailUtil.send(email);
        return viewContract.initialize(contract.getId());
    }
}
